package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Voice;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

/**
 * @Description:
 * @Create by: wanglei
 * @Date: 2021/11/6 18:43
 */
@DubboService
public class VoiceApiImpl implements VoiceApi{

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;


    //保存语音
    @Override
    public String saveVoice(Voice voice) {
        //1、设置属性
        voice.setTid(idWorker.getNextId("voice"));
        mongoTemplate.save(voice);
        String id = voice.getId().toHexString();
        return id;
    }

    //随机推荐一条语音
    @Override
    public Voice randomShow() {
        //1、创建统计对象，设置统计参数，随机推荐1条
        TypedAggregation aggregation = Aggregation.newAggregation(Voice.class,Aggregation.sample(1));
        //2、调用mongoTemplate方法统计
        AggregationResults<Voice> results = mongoTemplate.aggregate(aggregation, Voice.class);
        //3、获取统计结果
        return results.getMappedResults().get(0);
    }

    //删除一条语音
    @Override
    public void delete(Long userId, Long tid) {
        Criteria criteria = Criteria.where("userId").is(userId).and("tid").is(tid);
        mongoTemplate.remove(Query.query(criteria), Voice.class);
    }
}
